import {
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
  Get,
  Res,
  Ip,
  Body,
} from '@nestjs/common';
import { Response } from 'express';
import { FileInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service';
import { join, relative } from 'path';
import { ToolsService } from 'src/utils/tools.service';
import { ApiTags } from '@nestjs/swagger';

// import { createReadStream } from 'fs';

@ApiTags('上传模块')  
@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  //文件上传
  @Post()
  @UseInterceptors(FileInterceptor('file')) //获取header的file文件
  //从UploadedFile可获取
  async upload(@UploadedFile() file, @Body() body) {
    try {
      //图片命名空间
      const namespace = body.namespace
        ? body.namespace.replace(/\s+/g, '')
        : '';
      //获取文件相对路径
      // const STATIC_PATH = join(process.cwd());
      // const filePath = await relative(STATIC_PATH, file.path).replace(/\\/g, '/');
      const url = await this.uploadService.upload(file, namespace);
      return url;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  //文件下载
  @Get('export')
  async downloadAll(@Res() res: Response) {
    //基于流的下载方式
    const { filename, tarStream } = await this.uploadService.downloadAll();

    //设置响应to
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
    tarStream.pipe(res); //流转换到res响应
  }
}
